package com.definesys.smecrailtransit.module.SiteDetails;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.adapter.SelectMonthAdapter.SelectMonthAdapter;
import com.definesys.smecrailtransit.api.SmecRailApi;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseFragment;
import com.definesys.smecrailtransit.databinding.FragmentSiteDetailsBinding;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.DateController;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.EleFaultStatisticsFragment;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.EleRealTimeFragment;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.EleRuntimelengthFragment;
import com.definesys.smecrailtransit.module.SiteDetails.bean.EleAttentionBean;
import com.definesys.smecrailtransit.widget.Titanic.Titanic;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;

import java.util.ArrayList;
import java.util.HashMap;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

import static com.definesys.smecrailtransit.MainActivity.WAY_TO_FRAGMNET;

/**
 * Created by xupeizuo on 2017/8/21.
 */

public class SiteDetailsFragment extends SmecBaseFragment<SiteDetailsPresenter>{

    private FragmentSiteDetailsBinding fragmentSiteDetailsBinding;
    private ArrayList<Fragment> fragmentArrayList=new ArrayList<>();
    private int currentPage=0;

    public static final String SiteSwitch="SiteSwitch";
    public static final String REFRESH="REFRESH";
    public static final String CHANGE_MONTH="changeMonthSD()";


    private HashMap<String,Object> map=new HashMap<>();
    private int stationId=12335;
    private String date="";

    private SiteDetailsViewModel siteDetailsViewModel;

    private DateController formController;
    private DateController timeController;
    private SelectMonthAdapter selectMonthAdapter;
    private Titanic titanic;

    @Override
    protected SiteDetailsPresenter getPersenter() {
        return new SiteDetailsPresenter(getActivity());
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentSiteDetailsBinding=DataBindingUtil.inflate(inflater, R.layout.fragment_site_details,container,false);
        siteDetailsViewModel=new SiteDetailsViewModel(getActivity(),fragmentSiteDetailsBinding,mRxBus);
        _initView();
        fragmentSiteDetailsBinding.setSiteModel(siteDetailsViewModel);
        return fragmentSiteDetailsBinding.getRoot();
    }

    private void _initView(){

        _setAttentionMsg();
        schedulerThread(Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                _setMonth();
                _setCurrentMonth();
                _setMonthClick();
            }
        })).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
            }
        });
        _initViewPage();
    }

    /**
     * 初始化Viewpage
     */
    private void _initViewPage(){

        fragmentArrayList.add(EleRealTimeFragment.newInstance(mPresenter));
        fragmentArrayList.add(EleFaultStatisticsFragment.newInstance(mPresenter));
        fragmentArrayList.add(EleRuntimelengthFragment.newInstance(mPresenter));

        fragmentSiteDetailsBinding.viewPage.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentArrayList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentArrayList.size();
            }
        });
        fragmentSiteDetailsBinding.viewPage.setOffscreenPageLimit(fragmentArrayList.size());
        fragmentSiteDetailsBinding.viewPage.setPageMargin(40);
        fragmentSiteDetailsBinding.viewPage.setCurrentItem(currentPage,false);
        fragmentSiteDetailsBinding.viewPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPage=position;
                fragmentSiteDetailsBinding.title.setText(SmecRailConstant.getTitleArrayList().get(position));
                if(titanic == null){
                    titanic = new Titanic();
                }
                titanic.start(fragmentSiteDetailsBinding.title);
                fragmentSiteDetailsBinding.title.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        titanic.cancel();
                    }
                },1000);
                if(position ==0){
                    fragmentSiteDetailsBinding.siteMonth.setVisibility(View.INVISIBLE);
                }else {
                    fragmentSiteDetailsBinding.siteMonth.setVisibility(View.VISIBLE);
                }
                map.put("way","1");
                refresh();
                setMonth();
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 设置关注信息
     */
    private void _setAttentionMsg(){
        EleAttentionBean eleAttentionBean=mPresenter.getAttention();
        siteDetailsViewModel._initTitle();
        if(eleAttentionBean!=null && eleAttentionBean.getStationId()!=0 && eleAttentionBean.getStationName()!=null){
            stationId=eleAttentionBean.getStationId();
            siteDetailsViewModel.setStationsName(eleAttentionBean.getStationName());
            fragmentSiteDetailsBinding.siteSwitched.setText(eleAttentionBean.getStationName());
        }
    }

    /**
     * 设置月份信息
     */
    private void _setMonth(){
        formController = new DateController(SmecRailApi.MonthCode.MONTHFORM);
        timeController = new DateController(SmecRailApi.MonthCode.STATUSTIME);
        selectMonthAdapter = new SelectMonthAdapter(formController.getSelectMonth(),
                formController.getNowMonth(),this.getContext(),this.mRxBus, formController.getType());
        fragmentSiteDetailsBinding.gridView.setAdapter(selectMonthAdapter);
    }

    /**
     * 设置当前月份
     */
    private void _setCurrentMonth(){
        String[] nowStr=SmecRailConstant.getNowTime().split(" ")[0].split("-");
        date=nowStr[0]+"-"+nowStr[1];
    }

    /**
     * 设置日历点击事件
     */
    private void _setMonthClick(){
        //设置日历的点击事件
        fragmentSiteDetailsBinding.choiceMonth.setOnClickListener(v -> {
            if(fragmentSiteDetailsBinding.choice.getVisibility() == View.VISIBLE){
                fragmentSiteDetailsBinding.choice.setVisibility(View.GONE);
            }else{
                fragmentSiteDetailsBinding.choice.setVisibility(View.VISIBLE);
            }
        });
        fragmentSiteDetailsBinding.backgroundChoice.setOnClickListener(v -> fragmentSiteDetailsBinding.choice.setVisibility(View.GONE));
    }


    /**
     * 当站点以及日期改变时 刷新数据
     */
    public void refresh(){
        map.put("position",currentPage);
        map.put("stationId",stationId);
        map.put("date",date);
        mRxBus.post(SiteSwitch,map);
    }

    /**
     * 改变日期是刷新数据
     */
    private void changeMonth(){
        map.clear();
        refresh();
    }

    private void setMonth(){

        if(currentPage == 1){
            fragmentSiteDetailsBinding.nowMonth.setText(formController.getSelectYear()+"年 "+formController.getSelectMonth()+"月");
            selectMonthAdapter.selectMonth = formController.getSelectMonth();
            selectMonthAdapter.setType(SmecRailApi.MonthCode.STATUSFORM);
            if(formController.getSelectMonth().equals("7")){
                fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.GONE);
                fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.VISIBLE);
            }
            if(formController.getSelectMonth().equals(formController.getNowMonth())){
                fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.VISIBLE);
                fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.GONE);
            }
            fragmentSiteDetailsBinding.selectPreviousMonth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!formController.getSelectMonth().equals("7")){
                        formController.setSlectMonth( String.valueOf(Integer.valueOf(formController.getSelectMonth()) -1));
                        selectMonthAdapter.selectMonth = formController.getSelectMonth();
                        selectMonthAdapter.notifyDataSetChanged();
                        fragmentSiteDetailsBinding.nowMonth.setText(formController.getSelectYear()+"年 "+formController.getSelectMonth()+"月");

                        if(fragmentSiteDetailsBinding.selectNextMonthImg.getVisibility() == View.GONE){
                            fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.VISIBLE);
                        }

                        if(formController.getSelectMonth().equals("7")){
                            fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.GONE);
                        }
                        if(formController.getSelectMonth().equals("10")||
                                formController.getSelectMonth().equals("11")||
                                formController.getSelectMonth().equals("12"))
                        {
                            date=formController.getSelectYear()+"-"+formController.getSelectMonth();
                        }else {
                            date=formController.getSelectYear()+"-0"+formController.getSelectMonth();
                        }
                        changeMonth();
                        fragmentSiteDetailsBinding.choice.setVisibility(View.GONE);
                        fragmentSiteDetailsBinding.invalidateAll();
                    }
                }
            });

            fragmentSiteDetailsBinding.selectNextMonth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!formController.getSelectMonth().equals(formController.getNowMonth())){
                        formController.setSlectMonth(String.valueOf(Integer.valueOf(formController.getSelectMonth()) + 1));
                        selectMonthAdapter.selectMonth = formController.getSelectMonth();
                        selectMonthAdapter.notifyDataSetChanged();
                        fragmentSiteDetailsBinding.nowMonth.setText(formController.getSelectYear()+"年 "+formController.getSelectMonth()+"月");

                        if(fragmentSiteDetailsBinding.selectPreviousMonthImg.getVisibility() == View.GONE){
                            fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.VISIBLE);
                        }

                        if(formController.getSelectMonth().equals(formController.getNowMonth())){
                            fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.GONE);
                        }
                        if(formController.getSelectMonth().equals("10")||
                                formController.getSelectMonth().equals("11")||
                                formController.getSelectMonth().equals("12"))
                        {
                            date=formController.getSelectYear()+"-"+formController.getSelectMonth();
                        }else {
                            date=formController.getSelectYear()+"-0"+formController.getSelectMonth();
                        }
                        changeMonth();
                        fragmentSiteDetailsBinding.choice.setVisibility(View.GONE);
                        fragmentSiteDetailsBinding.invalidateAll();
                    }
                }
            });
        }
        if(currentPage == 2){
            fragmentSiteDetailsBinding.nowMonth.setText(timeController.getSelectYear()+"年 "+timeController.getSelectMonth()+"月");
            selectMonthAdapter.selectMonth = timeController.getSelectMonth();
            selectMonthAdapter.setType(SmecRailApi.MonthCode.STATUSTIME);
            if(timeController.getSelectMonth().equals("7")){
                fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.GONE);
                fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.VISIBLE);
            }
            if(timeController.getSelectMonth().equals(timeController.getNowMonth())){
                fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.VISIBLE);
                fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.GONE);
            }
            fragmentSiteDetailsBinding.selectPreviousMonth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!timeController.getSelectMonth().equals("7")){
                        timeController.setSlectMonth( String.valueOf(Integer.valueOf(timeController.getSelectMonth()) -1));
                        selectMonthAdapter.selectMonth = timeController.getSelectMonth();
                        selectMonthAdapter.notifyDataSetChanged();
                        fragmentSiteDetailsBinding.nowMonth.setText(timeController.getSelectYear()+"年 "+timeController.getSelectMonth()+"月");

                        if(fragmentSiteDetailsBinding.selectNextMonthImg.getVisibility() == View.GONE){
                            fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.VISIBLE);
                        }

                        if(timeController.getSelectMonth().equals("7")){
                            fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.GONE);
                        }
                        if(timeController.getSelectMonth().equals("10")||
                                timeController.getSelectMonth().equals("11")||
                                timeController.getSelectMonth().equals("12"))
                        {
                            date=timeController.getSelectYear()+"-"+timeController.getSelectMonth();
                        }else {
                            date=timeController.getSelectYear()+"-0"+timeController.getSelectMonth();
                        }

                        changeMonth();
                        fragmentSiteDetailsBinding.choice.setVisibility(View.GONE);
                        fragmentSiteDetailsBinding.invalidateAll();
                    }
                }
            });

            fragmentSiteDetailsBinding.selectNextMonth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!timeController.getSelectMonth().equals(timeController.getNowMonth())){
                        timeController.setSlectMonth(String.valueOf(Integer.valueOf(timeController.getSelectMonth()) + 1));
                        selectMonthAdapter.selectMonth = timeController.getSelectMonth();
                        selectMonthAdapter.notifyDataSetChanged();
                        fragmentSiteDetailsBinding.nowMonth.setText(timeController.getSelectYear()+"年 "+timeController.getSelectMonth()+"月");

                        if(fragmentSiteDetailsBinding.selectPreviousMonthImg.getVisibility() == View.GONE){
                            fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.VISIBLE);
                        }

                        if(timeController.getSelectMonth().equals(timeController.getNowMonth())){
                            fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.GONE);
                        }
                        date=timeController.getSelectYear()+"-0"+timeController.getSelectMonth();
                        changeMonth();
                        fragmentSiteDetailsBinding.choice.setVisibility(View.GONE);
                        fragmentSiteDetailsBinding.invalidateAll();
                    }
                }
            });
        }

    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(REFRESH)
            }
    )
    public void refresh(HashMap<String,Object> hashMap){
        map.clear();
        stationId=(Integer) hashMap.get("stationId");
        refresh();
        HashMap<String,Object> update=new HashMap<>();
        update.put("stationId",stationId);
        update.put("stationName",hashMap.get("stationName"));
        mPresenter.updateAttention(update);
    }

    public static SiteDetailsFragment newInstance() {
        Bundle args = new Bundle();
        SiteDetailsFragment fragment = new SiteDetailsFragment();
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 从导航栏进入改Fragment 时 应该只让第一个Fragment刷新数据
     * @param position
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(WAY_TO_FRAGMNET)
            }
    )
    public void intFragment(String position){
        if(position.equals("1")){
//            if(!CommonUtils.notEmpty(fragmentArrayList)){
//                _initViewPage();
//            }
            fragmentSiteDetailsBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    refresh();
                }
            },300);
        }
    }

    /**
     * 月份切换
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_MONTH)
            }
    )
    public void changeMonth(HashMap<String,String> o){
        if(o.get("month").equals("7")){
            fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.GONE);
        }else {
            fragmentSiteDetailsBinding.selectPreviousMonthImg.setVisibility(View.VISIBLE);
        }

        if(o.get("month").equals(formController.getNowMonth())){
            fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.GONE);
        }else{
            fragmentSiteDetailsBinding.selectNextMonthImg.setVisibility(View.VISIBLE);
        }

        if(o.get("type").equals(SmecRailApi.MonthCode.STATUSFORM)){
            formController.setSlectMonth(o.get("month"));
            fragmentSiteDetailsBinding.nowMonth.setText(formController.getSelectYear()+"年 "+formController.getSelectMonth()+"月");
            if(formController.getSelectMonth().equals("10")||
                    formController.getSelectMonth().equals("11")||
                    formController.getSelectMonth().equals("12"))
            {
                date=formController.getSelectYear()+"-"+formController.getSelectMonth();
            }else {
                date=formController.getSelectYear()+"-0"+formController.getSelectMonth();
            }
        }
        if(o.get("type").equals(SmecRailApi.MonthCode.STATUSTIME)){
            timeController.setSlectMonth(o.get("month"));
            fragmentSiteDetailsBinding.nowMonth.setText(timeController.getSelectYear()+"年 "+timeController.getSelectMonth()+"月");
            if(timeController.getSelectMonth().equals("10")||
                    timeController.getSelectMonth().equals("11")||
                    timeController.getSelectMonth().equals("12"))
            {
                date=timeController.getSelectYear()+"-"+timeController.getSelectMonth();
            }else {
                date=timeController.getSelectYear()+"-0"+timeController.getSelectMonth();
            }
        }
        map.put("way","0");
        refresh();
        selectMonthAdapter.selectMonth = o.get("month");
        selectMonthAdapter.notifyDataSetChanged();
        fragmentSiteDetailsBinding.choice.setVisibility(View.GONE);
    }

}
